import React from 'react';
import { parse } from 'querystring';
import _ from 'lodash';
import moment from 'moment';
import { TextWithTags, utils } from '@/components/BaseTable';
import HeaderRenderer from '@/components/BaseTable/HeaderRenderer';
/* eslint no-useless-escape:0 import/prefer-default-export:0 */

export const getArrayNumbers = (text, division = 1) => {
  if (!_.isEmpty(text) && text.indexOf('/') > -1) {
    // text.split('/')
    const temp = [];
    _.forEach(text.split('/'), value => {
      temp.push((_.trim(value) * 1) / division);
    });
    text = temp;
  } else {
    text = (text * 1) / division;
  }

  return text;
};

export const setFixedColumn = (attributesCheckeds, currentYear, type, currentMonths) => {
  const fixedColumns = [];
  let key = '';
  // if 月合计 12 else 1
  const length = type === 'monthValue' ? 12 : 1;
  for (let i = 1; i <= length; i += 1) {
    if (!currentMonths || _.includes(currentMonths, i.toString())) {
      key = currentYear + type + i;
      if (attributesCheckeds.length) {
        // 供货计划套数
        if (_.includes(attributesCheckeds, '套数')) {
          fixedColumns.push({
            key: `${key}num`,
            dataKey: 'num',
            title: '',
            align: 'right',
            width: 100,
            headerRenderer: () => (
              <div>
                <HeaderRenderer type={1}>
                  <div>套数/车位数</div>
                  <div>(套/个)</div>
                </HeaderRenderer>
              </div>
            ),
            dataGetter: ({ rowData }) => {
              let text = '';
              if (type === 'overAllValueVO') {
                text = rowData.overAllValueVO.num;
              } else if (type === 'yearValueVO') {
                text = rowData.yearValueVO.num;
              } else {
                const data = _.filter(rowData.monthValue, {
                  name: `${currentYear}-${i < 10 ? '0' : ''}${i}`,
                });
                text = data.length ? data[0].num : '';
              }

              return utils.calculate.NumberView({
                cellData: getArrayNumbers(text),
                precision: 0,
              });
            },
          });
        }
        // 供货计划面积
        if (_.includes(attributesCheckeds, '面积')) {
          fixedColumns.push({
            key: `${key}saleArea`,
            dataKey: 'saleArea',
            title: '',
            align: 'right',
            headerRenderer: () => (
              <div>
                <div>可售面积</div>
                <div>(平米)</div>
              </div>
            ),
            width: 100,
            dataGetter: ({ rowData }) => {
              let text = '';
              if (type === 'overAllValueVO') {
                text = rowData.overAllValueVO.saleArea;
              } else if (type === 'yearValueVO') {
                text = rowData.yearValueVO.saleArea;
              } else {
                const data = _.filter(rowData.monthValue, {
                  name: `${currentYear}-${i < 10 ? '0' : ''}${i}`,
                });
                text = data.length ? data[0].saleArea : '';
              }
              const result = {
                text,
              };
              result.textFirst = true;
              if (rowData.isParking === 1) {
                return '';
              }
              return result;
            },
            cellRenderer: data => <TextWithTags {...data} />,
          });
        }
        // 供货计划均价
        if (_.includes(attributesCheckeds, '均价')) {
          fixedColumns.push({
            key: `${key}avgPrice`,
            dataKey: 'avgPrice',
            title: '',
            align: 'right',
            width: 130,
            headerRenderer: () => (
              <div>
                <HeaderRenderer type={2}>
                  <div>均价</div>
                  <div>(元/平米，个)</div>
                </HeaderRenderer>
              </div>
            ),
            dataGetter: ({ rowData }) => {
              let text = '';
              if (type === 'overAllValueVO') {
                text = rowData.overAllValueVO.avgPrice;
              } else if (type === 'yearValueVO') {
                text = rowData.yearValueVO.avgPrice;
              } else {
                const data = _.filter(rowData.monthValue, {
                  name: `${currentYear}-${i < 10 ? '0' : ''}${i}`,
                });
                text = data.length ? data[0].avgPrice : '';
              }

              return utils.calculate.NumberView({
                cellData: getArrayNumbers(text),
                precision: 0,
              });
            },
          });
        }
        if (_.includes(attributesCheckeds, '金额')) {
          fixedColumns.push({
            key: `${key}price`,
            dataKey: 'price',
            align: 'right',
            width: 200,
            headerRenderer: () => (
              <div>
                <HeaderRenderer type={3}>
                  <div>金额</div>
                  <div>(万元：合计/房源/车位)</div>
                </HeaderRenderer>
              </div>
            ),
            dataGetter: ({ rowData }) => {
              let text = '';
              if (type === 'overAllValueVO') {
                text = rowData.overAllValueVO.price;
              } else if (type === 'yearValueVO') {
                text = rowData.yearValueVO.price;
              } else {
                const data = _.filter(rowData.monthValue, {
                  name: `${currentYear}-${i < 10 ? '0' : ''}${i}`,
                });
                text = data.length ? data[0].price : '';
                // rowData.overallPlanAndActual.price
              }
              return utils.calculate.NumberView({
                cellData: getArrayNumbers(text, 10000),
                precision: 0,
              });
            },
          });
        }
        if (
          (moment(currentYear).isBefore(moment().format('YYYY')) ||
            moment(currentYear).isSame(moment().format('YYYY'))) &&
          (moment(`${currentYear}-${i < 10 ? '0' : ''}${i}`).isBefore(moment().format('YYYY-MM')) ||
            moment(`${currentYear}-${i < 10 ? '0' : ''}${i}`).isSame(moment().format('YYYY-MM')))
        ) {
          // 供货实际套数
          if (_.includes(attributesCheckeds, '套数')) {
            fixedColumns.push({
              key: `${key}actualNum`,
              dataKey: 'actualNum',
              title: '套数',
              align: 'right',
              width: 100,
              headerRenderer: () => (
                <div>
                  <HeaderRenderer type={1}>
                    <div>套数/车位数</div>
                    <div>(套/个)</div>
                  </HeaderRenderer>
                </div>
              ),
              dataGetter: ({ rowData }) => {
                let text = '';
                if (type === 'overAllValueVO') {
                  text = rowData.overAllValueVO.actualNum;
                } else if (type === 'yearValueVO') {
                  text = rowData.yearValueVO.actualNum;
                } else {
                  const data = _.filter(rowData.monthValue, {
                    name: `${currentYear}-${i < 10 ? '0' : ''}${i}`,
                  });
                  text = data.length ? data[0].actualNum : '';
                }

                return utils.calculate.NumberView({
                  cellData: getArrayNumbers(text),
                  precision: 0,
                });
              },
            });
          }
          // 供货实际面积
          if (_.includes(attributesCheckeds, '面积')) {
            fixedColumns.push({
              key: `${key}actualArea`,
              dataKey: 'actualArea',
              title: '面积',
              align: 'right',
              width: 100,
              headerRenderer: () => (
                <div>
                  <div>可售面积</div>
                  <div>(平米)</div>
                </div>
              ),
              dataGetter: ({ rowData }) => {
                let text = '';
                if (type === 'overAllValueVO') {
                  text = `${rowData.overAllValueVO.actualArea}`;
                } else if (type === 'yearValueVO') {
                  text = `${rowData.yearValueVO.actualArea}`;
                } else {
                  const data = _.filter(rowData.monthValue, {
                    name: `${currentYear}-${i < 10 ? '0' : ''}${i}`,
                  });
                  text = data.length ? data[0].actualArea : '';
                }
                const result = {
                  text,
                };
                result.textFirst = true;
                if (rowData.isParking === 1) {
                  return '';
                }
                return result;
              },
              cellRenderer: data => <TextWithTags {...data} />,
            });
          }
          // 供货实际均价
          if (_.includes(attributesCheckeds, '均价')) {
            fixedColumns.push({
              key: `${key}actualAveragePrice`,
              dataKey: 'actualAveragePrice',
              title: '均价',
              align: 'right',
              width: 130,
              headerRenderer: () => (
                <div>
                  <HeaderRenderer type={2}>
                    <div>均价</div>
                    <div>(元/平米，个)</div>
                  </HeaderRenderer>
                </div>
              ),
              dataGetter: ({ rowData }) => {
                let text = '';
                if (type === 'overAllValueVO') {
                  text = rowData.overAllValueVO.actualAveragePrice;
                } else if (type === 'yearValueVO') {
                  text = rowData.yearValueVO.actualAveragePrice;
                } else {
                  const data = _.filter(rowData.monthValue, {
                    name: `${currentYear}-${i < 10 ? '0' : ''}${i}`,
                  });
                  text = data.length ? data[0].actualAveragePrice : '';
                }

                return utils.calculate.NumberView({
                  cellData: getArrayNumbers(text),
                  precision: 0,
                });
              },
            });
          }
          // 供货实际货值
          if (_.includes(attributesCheckeds, '金额')) {
            fixedColumns.push({
              key: `${key}actualPrice`,
              dataKey: 'actualPrice',
              align: 'right',
              width: 180,
              headerRenderer: () => (
                <div>
                  <HeaderRenderer type={3}>
                    <div>金额</div>
                    <div>(万元：合计/房源/车位)</div>
                  </HeaderRenderer>
                </div>
              ),
              dataGetter: ({ rowData }) => {
                let text = '';
                if (type === 'overAllValueVO') {
                  text = rowData.overAllValueVO.actualPrice;
                } else if (type === 'yearValueVO') {
                  text = rowData.yearValueVO.actualPrice;
                } else {
                  const data = _.filter(rowData.monthValue, {
                    name: `${currentYear}-${i < 10 ? '0' : ''}${i}`,
                  });
                  text = data.length ? data[0].actualPrice : '';
                }

                return utils.calculate.NumberView({
                  cellData: getArrayNumbers(text, 10000),
                  precision: 0,
                });
              },
            });
          }
        }
      }
      if (
        (moment(currentYear).isBefore(moment().format('YYYY')) ||
          moment(currentYear).isSame(moment().format('YYYY'))) &&
        (moment(`${currentYear}-${i < 10 ? '0' : ''}${i}`).isBefore(moment().format('YYYY-MM')) ||
          moment(`${currentYear}-${i < 10 ? '0' : ''}${i}`).isSame(moment().format('YYYY-MM')))
      ) {
        fixedColumns.push({
          key: `${key}achievingRate`,
          dataKey: 'achievingRate',
          title: '',
          align: 'right',
          width: 120,
          dataGetter: ({ rowData }) => {
            let text = '';
            if (type === 'overAllValueVO') {
              const { achievingRate } = rowData.overAllValueVO;
              if (achievingRate === 'null' || _.isNull(achievingRate)) {
                text = '';
              }
              if (achievingRate) {
                if (achievingRate === '-') {
                  text = '-';
                } else {
                  text = `${(achievingRate * 100).toFixed(3)}%`;
                }
              }
              // text = `${
              //   rowData.overAllValueVO.achievingRate === 'null' ||
              //     _.isNull(rowData.overAllValueVO.achievingRate)
              //     ? ''
              //     : `${(rowData.overAllValueVO.achievingRate * 100).toFixed(3)}%`
              //   }`;
            } else if (type === 'yearValueVO') {
              const { achievingRate } = rowData.yearValueVO;
              if (achievingRate === 'null' || _.isNull(achievingRate)) {
                text = '';
              }
              if (achievingRate) {
                if (achievingRate === '-') {
                  text = '-';
                } else {
                  text = `${(achievingRate * 100).toFixed(3)}%`;
                }
              }
              // text = `${
              //   rowData.yearValueVO.achievingRate === 'null' ||
              //     _.isNull(rowData.yearValueVO.achievingRate)
              //     ? ''
              //     : `${(rowData.yearValueVO.achievingRate * 100).toFixed(3)}%`
              //   }`;
            } else {
              const data = _.filter(rowData.monthValue, {
                name: `${currentYear}-${i < 10 ? '0' : ''}${i}`,
              });
              if (data.length) {
                const { achievingRate } = data[0];
                if (achievingRate === 'null' || _.isNull(achievingRate)) {
                  text = '';
                }
                if (achievingRate) {
                  if (achievingRate === '-') {
                    text = '-';
                  } else {
                    text = `${(achievingRate * 100).toFixed(3)}%`;
                  }
                }
              } else {
                text = '';
              }
              // text = data.length
              //   ? `${
              //   data[0].achievingRate === 'null' || _.isNull(data[0].achievingRate)
              //     ? ''
              //     : `${(data[0].achievingRate * 100).toFixed(3)}%`
              //   }`
              //   : '';
            }
            const result = {
              text,
            };
            result.textFirst = true;
            return result;
          },
          cellRenderer: data => <TextWithTags {...data} />,
        });
      }
    }
  }

  return fixedColumns;
};
export const getFixedColumns = (attributesCheckeds, currentYear, currentMonths) => {
  let fixedColumns = [
    {
      key: 'name',
      dataKey: 'name',
      title: '',
      width: 300,
      frozen: 'left',
      headerRenderer: () => <div>分期/组团/业态/楼栋</div>,
      dataGetter: ({ rowData }) => {
        const text = rowData.name;
        const result = {
          text,
        };
        result.textFirst = true;
        if (rowData.isSupply === 0) {
          result.tags = [{ text: '未供', color: 'orange', border: true }];
        }
        if (rowData.isSupply === 1) {
          result.tags = [{ text: '已供', color: 'green' }];
        }

        if (rowData.isDelay === 1) {
          result.tags.unshift({ text: '延迟', color: 'red' });
        }
        return result;
      },
      cellRenderer: data => <TextWithTags {...data} />,
    },
  ];
  // 供货计划与实际
  fixedColumns = _.concat(
    fixedColumns,
    setFixedColumn(attributesCheckeds, currentYear, 'overAllValueVO'),
  );
  if (_.includes(currentMonths, '14'.toString())) {
    // 供货年合计
    fixedColumns = _.concat(
      fixedColumns,
      setFixedColumn(attributesCheckeds, currentYear, 'yearValueVO'),
    );
  }
  // 供货月合计
  fixedColumns = _.concat(
    fixedColumns,
    setFixedColumn(attributesCheckeds, currentYear, 'monthValue', currentMonths),
  );

  return fixedColumns;
};

export const getTitleTree = (attributesCheckeds = [], currentYear = '', currentMonths) => {
  const titleTree = [
    {
      name: '分期/组团/业态/楼栋',
      key: 'id',
      colspan: 1,
      rowspan: 5,
      frozen: 'left',
    },
    {
      name: '全盘供货计划与实际',
      key: 'supplyTime',
      rowspan: 2,
      children: [],
    },
  ];
  if (currentMonths.length > 0) {
    titleTree.push({
      name: '',
      isTabs: true,
      key: 'yearTotalCount',
      children: [],
    });
    // 全盘供货计划与实际
    titleTree[1].children.push({
      name: '供货计划',
      key: 'actualNum',
      colspan: attributesCheckeds.length,
    });
    // table header点击的年份
    const columns = [];
    // 显示年供货合计
    columns.push({
      name: `${currentYear}年供货合计`,
      key: `actualNum${currentYear}`,
      hidden: !_.includes(currentMonths, '14'),
      children: [
        {
          name: '供货计划',
          key: `${currentYear}actualNum`,
          colspan: attributesCheckeds.length,
        },
      ],
    });

    // 年供货合计 if currentYear之前或相同 + 供货实际 + 达成率
    if (
      moment(currentYear).isBefore(moment().format('YYYY')) ||
      moment(currentYear).isSame(moment().format('YYYY'))
    ) {
      // 全盘供货计划与实际
      titleTree[1].children.push(
        {
          name: '供货实际',
          key: 'actualArea',
          colspan: attributesCheckeds.length,
        },
        {
          name: '达成率',
          key: 'actualAveragePrice',
          colspan: 1,
          marginTop: 1,
          rowspan: 3,
        },
      );

      columns[0].children.push(
        {
          name: '供货实际',
          key: `${currentYear}actualArea`,
          colspan: attributesCheckeds.length,
        },
        {
          name: '达成率',
          key: `${currentYear}actualAveragePrice`,
          colspan: 1,
          marginTop: 0,
          rowspan: 3,
        },
      );
    }

    // 月供货合计 if 当前年月份之前或相同 显示年供货合计 供货计划 + 供货实际 + 达成率 else 供货计划
    for (let i = 1; i <= 12; i++) {
      columns.push({
        name: `${currentYear}-${i < 10 ? '0' : ''}${i}`,
        key: `${currentYear}actualNum${i}`,
        hidden: !_.includes(currentMonths, i.toString()),
        children: [
          {
            name: '供货计划',
            key: `${currentYear}actualNum${i}`,
            colspan: attributesCheckeds.length,
          },
        ],
      });

      if (
        moment(`${currentYear}-${i}`).isBefore(moment().format('YYYY-MM')) ||
        moment(`${currentYear}-${i}`).isSame(moment().format('YYYY-MM'))
      ) {
        columns[i].children.push(
          {
            name: '供货实际',
            key: `${currentYear}actualArea${i}`,
            colspan: attributesCheckeds.length,
          },
          {
            name: '达成率',
            key: `${currentYear}actualAveragePrice${i}`,
            colspan: 1,
            marginTop: 0,
            rowspan: 3,
          },
        );
      }
    }
    titleTree[2].children = columns;
  }

  return titleTree;
};
